package com.tangpian.framework.service.user;

import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.crypto.hash.SimpleHash;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.tangpian.framework.entity.Account;
import com.tangpian.framework.entity.User;
import com.tangpian.framework.repository.UserDao;

@Service
@Transactional(readOnly = true)
public class AccountService {

	private String algorithmName = "SHA-512";

	private String salt = "helloworld";

	private int iterations = 1024;

	@Autowired
	private UserDao userDao;

	public String getSalt() {
		return salt;
	}

	public int getIterations() {
		return iterations;
	}

	public User findUserByUsername(String username) {
		return userDao.findUserByUsername(username);
	}

	@Transactional(readOnly = false)
	public void register(User user) {
		String password = user.getPassword();
		String enPassword = new SimpleHash(algorithmName, password, getSalt(),
				getIterations()).toBase64();
		user.setPassword(enPassword);
		userDao.save(user);
	}

	public void login(Account account) {
		UsernamePasswordToken token = new UsernamePasswordToken(
				account.getUsername(), account.getPassword(),
				account.isRememberMe());

		SecurityUtils.getSubject().login(token);
	}
	
	public User getUser(String id) {
		return userDao.findOne(id);
	}
}
